<template>
  <ul class="list">
    <li
      class="item"
      v-for="item of letters"
      :key="item"
      :ref="item"
      @touchstart="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
      @click="handleLetterClick"
    >
      {{ item }}
    </li>
  </ul>
</template>

<script>
export default {
  name: 'CityAlphabet',
  props: {
    cities: Object
  },
  computed: {
    letters () {
      const letters = []
      //遍历cities对象得到所有的属性名然后在添加到letters数组中 -> ["A","b"....."Z"]
      for (let i in this.cities) {
        letters.push(i)
      }
      return letters
    }
  },
  data () {
    return {
      touchStatus: false,
      //提高性能一开始startY: 0,因为它得值是固定的，避免每次都在handleTouchMove方法内计算
      startY: 0,
      //提高性能设置一个初始值，做节流用
      timer: null
    }
  },
  updated () {
    //等到页面挂载完后，只要页面数据更新就计算A所在位置offsetTop得值
    this.startY = this.$refs["A"][0].offsetTop
  },
  methods: {
    //当我们点击了city页面右边的 a-z 后触发给父组件city，并把点击的文本值作为参数传递过去
    handleLetterClick (e) {
      this.$emit("change", e.target.innerText);
    },
    handleTouchStart () {
      this.touchStatus = true;
    },
    handleTouchMove (e) {
      if (this.touchStatus) {
        //防抖，如果tiemer已经存在了就清除
        if (this.timer) {
          clearTimeout (this.timer)
        }
        //如果没有就创建一个定时器并延迟8毫秒执行如果在这个时间里又做了同样的操作则清除上次的操作在执行这次做的操作
        this.timer = setTimeout(() => {
          const touchY = e.touches[0].clientY - 84;
          const index = Math.floor((touchY - this.startY) / 20);
          if (index >= 0 && index < this.letters.length) {
            this.$emit("change", this.letters[index]);
          }
        }, 8)
      }
    },
    handleTouchEnd() {
      this.touchStatus = false;
    }
  }
}
</script>

<style lang="less" scoped>
.list {
  display: flex;
  flex-direction: column;
  justify-content: center;
  position: absolute;
  top: 0.84rem;
  right: 0;
  bottom: 0;
  width: 0.2rem;
  .item {
    font-size: 0.12rem;
    line-height: 0.2rem;
    text-align: center;
    color: #d20a0a;
  }
}
</style>
